package com.weds.frame.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/18 09:17
 */
@Service
@Slf4j
public class TokenUtil {

    @Autowired
    HttpServletRequest request;
    @Autowired
    TokenService tokenService;

    /**
     * 从request的token中获取用户ID
     *
     * @return
     */
    public Integer getUserId() {
        try {
//            String data = request.getHeader("pdata");
            String data = (String) request.getAttribute("pdata");
//            String data = AuthInterceptor.authorizationToken(tokenService, request, response);
            if (!"-1".equals("data")) {
                return JSON.parseObject(data).getInteger("userID");
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 从request的token中获取用户名
     *
     * @return
     */
    public String getUserName() {
        try {
//            String data = request.getHeader("pdata");
            String data = (String) request.getAttribute("pdata");
//            String data = AuthInterceptor.authorizationToken(tokenService, request, response);
            if (!"-1".equals("data")) {
                return JSON.parseObject(data).getString("userName");
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    public JSONObject getTokenData(){
        try{
            String data = (String) request.getAttribute("pdata");
            if (!"-1".equals("data")) {
                return JSON.parseObject(data);
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }

    /**
     * 从request的token中获取client
     *
     * @return
     */
    public String getClient() {
        try {
            String data = (String) request.getAttribute("pdata");
//            String data = request.getHeader("pdata");
//            String data = AuthInterceptor.authorizationToken(tokenService, request, response);
            if (!"-1".equals("data")) {
                return JSON.parseObject(data).getString("Client");
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
